package com.zhou.windpdfdownload;

import java.sql.*;
import java.util.Date;

public class MyAccessDataBase {
    private static String dbpath = "./output/data.accdb";// 路径
    private static String dbname = "";// 用户名
    private static String dbpassword = "";// 密码
    private static String url = "jdbc:access:///" + dbpath;// url

    public MyAccessDataBase() {

    }

    /**
     * 存储url和title
     *
     * @param url
     * @param title
     */
    public static void addUrl2title(String url, String title) {
        Connection conn = connectDataBase();

        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from url2title where url='" + url + "'");
            if(rs != null && rs.next() == false){
                String sql = "insert into url2title (url, title) values (?, ?)";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, url);
                pstmt.setString(2, title);
                pstmt.execute();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        closeConnection(conn);
    }

    /**
     * 通过url查询标题
     *
     * @param url
     * @return
     */
    public static String getTitleByUrl(String url) {
        Connection conn = connectDataBase();
        String title = null;

        String sql = "select title from url2title where url='" + url + "'";
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.next()) {
                title = rs.getString("title");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        closeConnection(conn);

        if (title == null) {
            title = new Date().getTime() + ".pdf";
        }
        return title;
    }

    /**
     * 连接数据库
     */
    public static Connection connectDataBase() {
        try {
            Class.forName("com.hxtt.sql.access.AccessDriver");
            return DriverManager.getConnection(url, dbname, dbpassword);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭数据库
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
